<template>
  <div class="app-container">
    <h4>报销申请</h4>
    <el-button type="primary" @click="handleApplyReimbursement">申请报销</el-button>
    <p>这里将显示用户的报销申请记录和状态。</p>

    <el-table v-loading="loading" :data="tasks.reimbursements" style="width: 100%">
      <el-table-column prop="expenseType" label="费用类型"></el-table-column>
      <el-table-column prop="amount" label="报销金额"></el-table-column>
      <el-table-column prop="description" label="费用说明"></el-table-column>
      <el-table-column label="状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="statusTag(scope.row.status)" >{{ statusOptions.find(s => s.value === scope.row.status) ? statusOptions.find(s => s.value === scope.row.status).label : '' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="拒绝原因" align="center" prop="rejectReason" />
      <el-table-column label="申请时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="附件" align="center" prop="attachment">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.attachment"
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownloadAllAttachments(scope.row.attachment)"
          >下载全部附件</el-button>
          <span v-else>无附件</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getReimbursements"
    />





    
    <el-dialog :title="title" :visible.sync="dialogVisible" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="费用类型" prop="expenseType">
          <el-select v-model="form.expenseType" placeholder="请选择费用类型">
            <el-option
              v-for="item in expenseTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报销金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入报销金额" />
        </el-form-item>
        <el-form-item label="费用说明" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            ref="upload"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="true"
            multiple
          >
            <el-button size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">可上传多个jpg/png文件，且每个不超过500kb</div>
          </el-upload>
        </el-form-item>
       <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listReimbursement, getReimbursement, addReimbursement, updateReimbursement, delReimbursement } from "@/api/operations/reimbursement";
import { getToken } from "@/utils/auth";
import Pagination from "@/components/Pagination";
import { parseTime } from '@/utils/ruoyi';
import { download } from '@/utils/download';

export default {
  name: "ReimbursementApply",
  components: { Pagination },
  props: {
    userId: {
      type: [String, Number],
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 当前页数
      pageNum: 1,
      // 每页显示条数
      pageSize: 10,
      showSearch: true,
      tasks: {
        reimbursements: [],
      },
      title: "",
      dialogVisible: false,
      form: {
        id: null,
        expenseType: null,
        amount: null,
        description: null,
        attachment: null
      },
      upload: {
        isUploading: false,
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/operations/reimbursement/upload",
        fileList: []
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        expenseType: null,
        status: null,
        applicantId: null // Initialize as null; will be set by watcher
      },
      rules: {
        expenseType: [
          { required: true, message: "费用类型不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "报销金额不能为空", trigger: "blur" }
        ],
        description: [
          { required: true, message: "费用说明不能为空", trigger: "blur" }
        ]
      },
      expenseTypeOptions: [
        { value: '差旅费', label: '差旅费' },
        { value: '交通费', label: '交通费' },
        { value: '餐饮费', label: '餐饮费' },
        { value: '办公用品', label: '办公用品' },
        { value: '通讯费', label: '通讯费' },
        { value: '培训费', label: '培训费' },
        { value: '会议费', label: '会议费' },
        { value: '业务招待费', label: '业务招待费' },
        { value: '设备购置费', label: '设备购置费' },
        { value: '其他费用', label: '其他费用' }
      ],
      statusOptions: [
        { value: 0, label: '草稿' },
        { value: 1, label: '已提交' },
        { value: 2, label: '已批准' },
        { value: 3, label: '已拒绝' },
        { value: 4, label: '已付款' }
      ]
    };
  },
   created() {
    // Initial fetch if userId is already available, otherwise watcher will trigger it
    if (this.userId) {
      this.queryParams.applicantId = this.userId;
      this.getReimbursements();
    }
  },
  watch: {
    userId(newVal, oldVal) {
      if (newVal !== oldVal && newVal) {
        this.queryParams.applicantId = newVal;
        this.getReimbursements();
      }
    }
  },
  methods: {
    parseTime,
    getReimbursements() {
      this.loading = true;
      console.log("获取报销申请列表",this.queryParams);
      listReimbursement(this.queryParams).then(response => {
        this.tasks.reimbursements = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    statusTag(status) {
        if (status === 0) return 'info';
        if (status === 1) return 'success';
        if (status === 2) return 'success';
        if (status === 3) return 'danger';
        if (status === 4) return 'success';
        return '';
    },
    handleApplyReimbursement() {
      this.reset();
      this.dialogVisible = true;
      this.title = "添加报销申请";
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      if (response.code === 200) {
        if (this.form.attachment) {
          this.form.attachment += ',' + response.url; 
        } else {
          this.form.attachment = response.url; 
        }
        this.$modal.msgSuccess("上传成功");
      } else {
        this.$modal.msgError(response.msg || "上传失败");
      }
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const dataToSend = {
            ...this.form,
            applicantId: this.userId
          };

          if (this.form.id != null) {
            updateReimbursement(dataToSend).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dialogVisible = false;
              this.getReimbursements();
            }).catch(error => {
              this.$modal.msgError("修改失败: " + (error.msg || error.message));
            });
          } else {
            addReimbursement(dataToSend).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialogVisible = false;
              this.getReimbursements();
            }).catch(error => {
              this.$modal.msgError("新增失败: " + (error.msg || error.message));
            });
          }
        }
      });
    },
    cancel() {
      this.dialogVisible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        expenseType: null,
        amount: null,
        description: null,
        attachment: null,
        remark: null
      };
      this.upload.fileList = [];
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getReimbursements();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getReimbursement(row.id).then(response => {
        this.form = response.data;
        this.upload.fileList = [];
        if (this.form.attachment) {
          this.form.attachment.split(',').forEach((url, index) => {
            this.upload.fileList.push({ name: `附件${index + 1}`, url: url });
          });
        }
        this.dialogVisible = true;
        this.title = "修改报销申请";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除该条报销申请？').then(function() {
        return delReimbursement(row.id);
      }).then(() => {
        this.getReimbursements();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/operations/reimbursement/export', {
        ...this.queryParams,
        applicantId: this.userId // Ensure filtering by current user for export
      }, `reimbursement_${new Date().getTime()}.xlsx`);
    },
    /** 下载附件 */
    handleDownload(url) {
      window.open(url, '_blank');
    }
  }
};
</script>
<style>
.app-container {
  padding: 20px;
}
</style> 